import 'package:flutter/material.dart';
import 'package:get/get.dart';
import './controller.dart';
import '../../../common/models/server_model.dart';
import '../../../common/routers/names.dart';

class ServerDetailView extends GetView<ServerDetailController> {
  const ServerDetailView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios),
          onPressed: () {
            Get.back();
          },
        ),
        title: Obx(() => Text(controller.server.value?.name ?? '服务器详情')),
        actions: [
          // 连接/断开按钮
          Obx(() {
            if (controller.isConnected.value) {
              return IconButton(
                icon: const Icon(Icons.power_off),
                onPressed: controller.disconnect,
                tooltip: '断开连接',
              );
            } else {
              return IconButton(
                icon: const Icon(Icons.power),
                onPressed: controller.connect,
                tooltip: '连接服务器',
              );
            }
          }),
          // 刷新按钮
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: controller.fetchMonitoringData,
            tooltip: '刷新监控数据',
          ),
          // 删除按钮
          IconButton(
            icon: const Icon(Icons.delete_outline),
            onPressed: controller.deleteServer,
            tooltip: '删除服务器',
          ),
        ],
      ),
      body: Obx(() {
        if (controller.isLoading.value && controller.statusData.value == null) {
          return const Center(child: CircularProgressIndicator());
        }

        if (controller.server.value == null) {
          return const Center(child: Text('服务器信息加载失败或不存在。'));
        }

        return RefreshIndicator(
          onRefresh: controller.fetchMonitoringData,
          child: SingleChildScrollView(
            physics: const AlwaysScrollableScrollPhysics(),
            padding: const EdgeInsets.all(12.0),  // 紧凑内边距：16 -> 12
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 连接信息卡片
                _buildConnectionCard(),
                const SizedBox(height: 12),  // 紧凑间距：16 -> 12
                
                // 监控指标卡片
                if (controller.isConnected.value) ...[
                  _buildMonitoringCard(),
                  const SizedBox(height: 12),  // 紧凑间距：16 -> 12
                  // Docker 管理卡片
                  _buildDockerCard(),
                  const SizedBox(height: 12),  // 紧凑间距：16 -> 12
                  // K8s 管理卡片
                  _buildK8sCard(),
                  const SizedBox(height: 12),  // 紧凑间距：16 -> 12
                  // 文件管理器卡片
                  _buildFilesCard(),
                  const SizedBox(height: 12),  // 紧凑间距：16 -> 12
                  // 快捷命令卡片
                  _buildCommandsCard(),
                ] else ...[
                  _buildDisconnectedCard(),
                ],
                
                // 错误信息
                if (controller.errorMessage.value.isNotEmpty) ...[
                  const SizedBox(height: 12),  // 紧凑间距：16 -> 12
                  _buildErrorCard(),
                ],
              ],
            ),
          ),
        );
      }),
    );
  }

  /// 构建连接信息卡片
  Widget _buildConnectionCard() {
    return Card(
      elevation: 2,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: Padding(
        padding: const EdgeInsets.all(12.0),  // 紧凑内边距：16 -> 12
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                const Text(
                  '连接信息',
                  style: TextStyle(fontSize: 15, fontWeight: FontWeight.bold),  // 紧凑字体：18 -> 15
                ),
                const Spacer(),
                // 终端按钮
                Obx(() {
                  if (controller.isConnected.value) {
                    return IconButton(
                      icon: const Icon(Icons.terminal, size: 20),
                      onPressed: () {
                        Get.toNamed(
                          RouteNames.homeTerminal,
                          parameters: {'id': controller.serverId},
                        );
                      },
                      tooltip: '打开终端',
                      padding: const EdgeInsets.all(4),
                      constraints: const BoxConstraints(minWidth: 32, minHeight: 32),
                    );
                  }
                  return const SizedBox.shrink();
                }),
                const SizedBox(width: 8),
                Obx(() => _buildStatusChip(controller.server.value!.status)),
              ],
            ),
            const Divider(height: 20),  // 紧凑高度：24 -> 20
            _buildInfoRow('名称', controller.server.value!.name),
            const SizedBox(height: 6),  // 紧凑间距：8 -> 6
            _buildInfoRow('地址', controller.server.value!.connectionString),
            const SizedBox(height: 6),  // 紧凑间距：8 -> 6
            _buildInfoRow('用户名', controller.server.value!.username),
            if (controller.server.value!.lastConnectedAt != null) ...[
              const SizedBox(height: 6),  // 紧凑间距：8 -> 6
              _buildInfoRow(
                '最后连接',
                _formatDateTime(controller.server.value!.lastConnectedAt!),
              ),
            ],
          ],
        ),
      ),
    );
  }

  /// 构建监控指标卡片
  Widget _buildMonitoringCard() {
    return Obx(() {
      final data = controller.statusData.value;
      
      if (data == null) {
        return Card(
          elevation: 2,
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
          child: const Padding(
            padding: EdgeInsets.all(12.0),  // 紧凑内边距：16 -> 12
            child: Center(
              child: Text('暂无监控数据，请点击刷新按钮获取', style: TextStyle(fontSize: 12)),  // 字体：默认 -> 12
            ),
          ),
        );
      }

      return Card(
        elevation: 2,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
        child: InkWell(
          onTap: () {
            // 跳转到监控详情页面
            Get.toNamed(
              RouteNames.homeServerMonitor,
              parameters: {'id': controller.serverId},
            );
          },
          borderRadius: BorderRadius.circular(12),
          child: Padding(
            padding: const EdgeInsets.all(12.0),  // 紧凑内边距：16 -> 12
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
              Row(
                children: [
                  const Text(
                    '监控指标',
                    style: TextStyle(fontSize: 15, fontWeight: FontWeight.bold),  // 紧凑字体：18 -> 15
                  ),
                  const Spacer(),
                  Text(
                    _formatTime(data.timestamp),
                    style: TextStyle(fontSize: 11, color: Colors.grey[600]),  // 紧凑字体：12 -> 11
                  ),
                  const SizedBox(width: 6),  // 紧凑间距：8 -> 6
                  Icon(Icons.arrow_forward_ios, size: 14, color: Colors.grey[400]),  // 紧凑图标：16 -> 14
                ],
              ),
              const Divider(height: 20),  // 紧凑高度：24 -> 20
              
              // CPU 使用率
              _buildMetricRow(
                'CPU 使用率',
                '${data.cpuUsage.toStringAsFixed(1)}%',
                data.cpuUsage.toDouble(),
                Icons.memory,
              ),
              const SizedBox(height: 12),  // 紧凑间距：16 -> 12
              
              // 内存使用率
              _buildMetricRow(
                '内存使用率',
                '${data.memoryUsage.toStringAsFixed(1)}% (${_formatBytes(data.usedMemory)}/${_formatBytes(data.totalMemory)})',
                data.memoryUsage.toDouble(),
                Icons.memory_outlined,
              ),
              const SizedBox(height: 12),  // 紧凑间距：16 -> 12
              
              // 磁盘使用率
              _buildMetricRow(
                '磁盘使用率',
                '${data.diskUsage.toStringAsFixed(1)}% (${_formatBytes(data.usedDisk)}/${_formatBytes(data.totalDisk)})',
                data.diskUsage.toDouble(),
                Icons.storage,
              ),
              
              // 系统信息
              if (data.osVersion != null || data.hostname != null || data.uptime != null) ...[
                const Divider(height: 24),  // 紧凑高度：32 -> 24
                const Text(
                  '系统信息',
                  style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold),  // 紧凑字体：16 -> 14
                ),
                const SizedBox(height: 10),  // 紧凑间距：12 -> 10
                if (data.hostname != null) ...[
                  _buildInfoRow('主机名', data.hostname!),
                  const SizedBox(height: 6),  // 紧凑间距：8 -> 6
                ],
                if (data.osVersion != null) ...[
                  _buildInfoRow('操作系统', data.osVersion!),
                  const SizedBox(height: 6),  // 紧凑间距：8 -> 6
                ],
                if (data.uptime != null) ...[
                  _buildInfoRow('运行时间', data.uptime!),
                ],
              ],
            ],
          ),
        ),
      ),
      );
    });
  }

  /// 构建未连接卡片
  Widget _buildDisconnectedCard() {
    return Card(
      elevation: 2,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: Padding(
        padding: const EdgeInsets.all(24.0),  // 紧凑内边距：32 -> 24
        child: Center(
          child: Column(
            children: [
              Icon(Icons.cloud_off, size: 48, color: Colors.grey[400]),  // 紧凑图标：64 -> 48
              const SizedBox(height: 12),  // 紧凑间距：16 -> 12
              Text(
                '未连接到服务器',
                style: TextStyle(
                  fontSize: 14,  // 紧凑字体：16 -> 14
                  color: Colors.grey[600],
                  fontWeight: FontWeight.w500,
                ),
              ),
              const SizedBox(height: 6),  // 紧凑间距：8 -> 6
              Text(
                '点击右上角电源按钮连接',
                style: TextStyle(fontSize: 12, color: Colors.grey[500]),  // 紧凑字体：14 -> 12
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建错误信息卡片
  Widget _buildErrorCard() {
    return Card(
      elevation: 2,
      color: Colors.red[50],
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: Padding(
        padding: const EdgeInsets.all(12.0),  // 紧凑内边距：16 -> 12
        child: Row(
          children: [
            Icon(Icons.error_outline, size: 20, color: Colors.red[700]),  // 紧凑图标：24 -> 20
            const SizedBox(width: 10),  // 紧凑间距：12 -> 10
            Expanded(
              child: Text(
                controller.errorMessage.value,
                style: TextStyle(
                  color: Colors.red[700],
                  fontSize: 12,  // 紧凑字体：14 -> 12
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建状态徽章
  Widget _buildStatusChip(ServerStatus status) {
    final Color color;
    final String label;
    
    switch (status) {
      case ServerStatus.connected:
        color = Colors.green;
        label = '已连接';
        break;
      case ServerStatus.connecting:
        color = Colors.orange;
        label = '连接中';
        break;
      case ServerStatus.error:
        color = Colors.red;
        label = '错误';
        break;
      case ServerStatus.disconnected:
      default:
        color = Colors.grey;
        label = '未连接';
        break;
    }
    
    return Chip(
      label: Text(
        label,
        style: const TextStyle(color: Colors.white, fontSize: 10),  // 紧凑字体：12 -> 10
      ),
      backgroundColor: color,
      padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 0),  // 紧凑内边距：8 -> 6
      materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
    );
  }

  /// 构建信息行
  Widget _buildInfoRow(String label, String value) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        SizedBox(
          width: 70,  // 紧凑宽度：80 -> 70
          child: Text(
            '$label:',
            style: const TextStyle(fontWeight: FontWeight.w500, fontSize: 12),  // 紧凑字体：14 -> 12
          ),
        ),
        Expanded(
          child: Text(
            value,
            style: TextStyle(fontSize: 12, color: Colors.grey[700]),  // 紧凑字体：14 -> 12
          ),
        ),
      ],
    );
  }

  /// 构建指标行
  Widget _buildMetricRow(String label, String value, double percentage, IconData icon) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Icon(icon, size: 18, color: Colors.blue),  // 紧凑图标：20 -> 18
            const SizedBox(width: 6),  // 紧凑间距：8 -> 6
            Text(
              label,
              style: const TextStyle(fontWeight: FontWeight.w500, fontSize: 12),  // 紧凑字体：14 -> 12
            ),
            const Spacer(),
            Text(
              value,
              style: TextStyle(fontSize: 11, color: Colors.grey[700]),  // 紧凑字体：13 -> 11
            ),
          ],
        ),
        const SizedBox(height: 6),  // 紧凑间距：8 -> 6
        ClipRRect(
          borderRadius: BorderRadius.circular(4),
          child: LinearProgressIndicator(
            value: percentage / 100,
            backgroundColor: Colors.grey[200],
            valueColor: AlwaysStoppedAnimation<Color>(
              _getColorForPercentage(percentage),
            ),
            minHeight: 6,  // 紧凑高度：8 -> 6
          ),
        ),
      ],
    );
  }

  /// 根据百分比获取颜色
  Color _getColorForPercentage(double percentage) {
    if (percentage < 60) {
      return Colors.green;
    } else if (percentage < 80) {
      return Colors.orange;
    }
    return Colors.red;
  }

  /// 格式化字节大小
  String _formatBytes(int bytes) {
    if (bytes < 1024) {
      return '$bytes B';
    } else if (bytes < 1024 * 1024) {
      return '${(bytes / 1024).toStringAsFixed(1)} KB';
    } else if (bytes < 1024 * 1024 * 1024) {
      return '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB';
    } else {
      return '${(bytes / (1024 * 1024 * 1024)).toStringAsFixed(1)} GB';
    }
  }

  /// 格式化时间
  String _formatTime(DateTime dateTime) {
    final now = DateTime.now();
    final difference = now.difference(dateTime);

    if (difference.inSeconds < 60) {
      return '${difference.inSeconds} 秒前';
    } else if (difference.inMinutes < 60) {
      return '${difference.inMinutes} 分钟前';
    } else if (difference.inHours < 24) {
      return '${difference.inHours} 小时前';
    } else {
      return '${difference.inDays} 天前';
    }
  }

  /// 格式化日期时间
  String _formatDateTime(DateTime dateTime) {
    return '${dateTime.year}-${dateTime.month.toString().padLeft(2, '0')}-${dateTime.day.toString().padLeft(2, '0')} '
        '${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}';
  }

  /// 构建 Docker 管理卡片
  Widget _buildDockerCard() {
    return Card(
      elevation: 2,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: InkWell(
        onTap: () {
          // 跳转到 Docker 管理页面
          Get.toNamed(
            RouteNames.homeServerDocker,
            parameters: {'id': controller.serverId},
          );
        },
        borderRadius: BorderRadius.circular(12),
        child: Padding(
          padding: const EdgeInsets.all(12.0),  // 紧凑内边距：16 -> 12
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Icon(Icons.widgets, color: Colors.blue[700], size: 20),  // 紧凑图标：24 -> 20
                  const SizedBox(width: 10),  // 紧凑间距：12 -> 10
                  const Text(
                    'Docker 管理',
                    style: TextStyle(fontSize: 15, fontWeight: FontWeight.bold),  // 紧凑字体：18 -> 15
                  ),
                  const Spacer(),
                  Icon(Icons.arrow_forward_ios, size: 14, color: Colors.grey[400]),  // 紧凑图标：16 -> 14
                ],
              ),
              const SizedBox(height: 12),  // 紧凑间距：16 -> 12
              Text(
                '查看和管理服务器上的 Docker 容器',
                style: TextStyle(
                  fontSize: 12,  // 紧凑字体：14 -> 12
                  color: Colors.grey[600],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建 K8s 管理卡片
  Widget _buildK8sCard() {
    return Card(
      elevation: 2,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: InkWell(
        onTap: () {
          // 跳转到 K8s 管理页面
          Get.toNamed(
            RouteNames.homeServerK8s,
            parameters: {'id': controller.serverId},
          );
        },
        borderRadius: BorderRadius.circular(12),
        child: Padding(
          padding: const EdgeInsets.all(12.0),  // 紧凑内边距：16 -> 12
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Icon(Icons.cloud_queue, color: Colors.purple[700], size: 20),  // 紧凑图标：24 -> 20
                  const SizedBox(width: 10),  // 紧凑间距：12 -> 10
                  const Text(
                    'Kubernetes 管理',
                    style: TextStyle(fontSize: 15, fontWeight: FontWeight.bold),  // 紧凑字体：18 -> 15
                  ),
                  const Spacer(),
                  Icon(Icons.arrow_forward_ios, size: 14, color: Colors.grey[400]),  // 紧凑图标：16 -> 14
                ],
              ),
              const SizedBox(height: 12),  // 紧凑间距：16 -> 12
              Text(
                '查看和管理服务器上的 Kubernetes 集群和 Pods',
                style: TextStyle(
                  fontSize: 12,  // 紧凑字体：14 -> 12
                  color: Colors.grey[600],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建文件管理器卡片
  Widget _buildFilesCard() {
    return Card(
      elevation: 2,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: InkWell(
        onTap: () {
          // 跳转到文件管理器页面
          Get.toNamed(
            RouteNames.homeServerFiles,
            parameters: {'id': controller.serverId},
          );
        },
        borderRadius: BorderRadius.circular(12),
        child: Padding(
          padding: const EdgeInsets.all(12.0),  // 紧凑内边距：16 -> 12
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Icon(Icons.folder_open, color: Colors.orange[700], size: 20),  // 紧凑图标：24 -> 20
                  const SizedBox(width: 10),  // 紧凑间距：12 -> 10
                  const Text(
                    '文件管理器',
                    style: TextStyle(fontSize: 15, fontWeight: FontWeight.bold),  // 紧凑字体：18 -> 15
                  ),
                  const Spacer(),
                  Icon(Icons.arrow_forward_ios, size: 14, color: Colors.grey[400]),  // 紧凑图标：16 -> 14
                ],
              ),
              const SizedBox(height: 12),  // 紧凑间距：16 -> 12
              Text(
                '浏览、上传、下载和编辑服务器文件',
                style: TextStyle(
                  fontSize: 12,  // 紧凑字体：14 -> 12
                  color: Colors.grey[600],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建快捷命令卡片
  Widget _buildCommandsCard() {
    return Card(
      elevation: 2,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: InkWell(
        onTap: () {
          // 跳转到快捷命令页面
          Get.toNamed(
            RouteNames.homeServerCommands,
            parameters: {'id': controller.serverId},
          );
        },
        borderRadius: BorderRadius.circular(12),
        child: Padding(
          padding: const EdgeInsets.all(12.0),  // 紧凑内边距：16 -> 12
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Icon(Icons.bolt, color: Colors.amber[700], size: 20),  // 紧凑图标：24 -> 20
                  const SizedBox(width: 10),  // 紧凑间距：12 -> 10
                  const Text(
                    '快捷命令',
                    style: TextStyle(fontSize: 15, fontWeight: FontWeight.bold),  // 紧凑字体：18 -> 15
                  ),
                  const Spacer(),
                  Icon(Icons.arrow_forward_ios, size: 14, color: Colors.grey[400]),  // 紧凑图标：16 -> 14
                ],
              ),
              const SizedBox(height: 12),  // 紧凑间距：16 -> 12
              Text(
                '快速执行常用命令和脚本',
                style: TextStyle(
                  fontSize: 12,  // 紧凑字体：14 -> 12
                  color: Colors.grey[600],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

}
